package com.db.bankapp.service;

import com.db.bankapp.domain.Account;
import com.db.bankapp.domain.Bank;
import com.db.bankapp.domain.Client;

import java.io.*;

/**
 * @ThreadSafe (relies on underlying classes)
 * Provider of bank services
 * Created by Student on 18.08.2014.
 */
public class BankService {

    /**
     * Adds client to bank
     * @param bank to which add client
     * @param client to add to bank
     */
    public static void addClient(Bank bank, Client client) {
        bank.addClient(client);
    }

    /**
     * Return and prints maximum amount to withdraw in bank
     * @param bank in which to search
     * @return maximum amount to withdraw in bank
     */
    public static int printMaximumAmountToWithdraw(Bank bank) {
        int max = 0;
        for(Client client : bank.getClients()) {
            for (Account account : client.getAccounts()) {
                if (account.maximumAmountToWithdraw() > max) {
                    max = account.maximumAmountToWithdraw();
                }
            }
        }
        // todo: uncomment when better times come
        // buzzy ^.^
//        int max = bank.getClients().stream().map(
//                (client) -> client.getAccounts().stream()
//                        .map(Account::maximumAmountToWithdraw).max(Integer::compareTo).get())
//                .max(Integer::compareTo).get();
        System.out.println(max);
        return max;
    }
    /**
     * Writes bank in the file
     * @param bank to write, path to put
     */
    public static void saveBank(Bank bank,String path) {
        try(ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream(path))) {
            oos.writeObject(bank);
            System.out.println("The bank list was saved in " + path + " as bank.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * Return bank written in file
     * @param path where bank is put
     * @return bank from the path
     */
    public static Bank readBank(String path) {
        Bank bank=null;
        try(ObjectInputStream ois = new ObjectInputStream(
                new FileInputStream(path))) {
            bank = (Bank) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return bank;
    }
}
